﻿using SmarterCharger.Library.Infrastructure.Interfaces;
using SmarterCharger.Library.Model;
using SmarterCharger.Library.Repositories.Interfaces;
using SmarterCharger.Library.Services.Interfaces;
using System;
using System.Net;
using System.Threading.Tasks;

namespace SmarterCharger.Library.Services
{
    internal class SmartChargeStopper : ISmartChargeStopper
    {
        private const double DefaultChargeLimit = 100;

        private readonly ISettingsService _settingsService;
        private readonly IBattery _battery;
        private readonly ISmartPlugRepository _smartPlugRepository;

        public SmartChargeStopper(ISettingsService settingsService, IBattery battery, ISmartPlugRepository smartPlugRepository)
        {
            if (settingsService == null) throw new ArgumentNullException("settingsService");
            if (battery == null) throw new ArgumentNullException("battery");
            if (smartPlugRepository == null) throw new ArgumentNullException("smartPlugRepository");

            _settingsService = settingsService;
            _battery = battery;
            _smartPlugRepository = smartPlugRepository;
        }

        public Task<bool> Stop()
        {
            var remainingChargePercent = _battery.GetRemainingChargePercent();
            var chargeLimit = _settingsService.GetChargeLimit() ?? DefaultChargeLimit;

            if (remainingChargePercent < chargeLimit)
                return ContinueCharging();
            else
                return StopCharging();
        }

        private Task<bool> ContinueCharging()
        {
            //TODO: display current battery percentage on tile

            return Task.FromResult<bool>(false);
        }

        private async Task<bool> StopCharging()
        {
            var smartPlug = _settingsService.GetDefaultSmartPlug();
            //TODO: when smart plug is null, update tile, than exit

            var request = new SwitchSmartPlugRequest
            {
                Username = _settingsService.GetUsername(),
                Password = _settingsService.GetPassword(),
                SmartPlugId = smartPlug.EnergyDeviceId,
                IsOn = false
            };

            var result = await _smartPlugRepository.SwitchSmartPlug(request);
            switch (result.StatusCode)
            {
                case HttpStatusCode.NoContent:
                    //TODO: update tile with time when stopped charging and which battery percentage
                    return true;
              
                default:
                    //TODO: update tile with time when failed to stop charging
                    return false;
            }
        }
    }
}
